/**
 * @name api
 */
import { fetch } from "./index";
import Taro from "@tarojs/taro";

// 首页渲染接口
export const fetchList = async ({ page = 1, size = 5 }) => {
  const response = await fetch("http://localhost:9999/list", "GET", {
    _page: page,
    _limit: size,
  });
  return response.data;
};

// 购物车页面渲染接口
export const fetchCartList = async ({ page = 1, size = 5 }) => {
  const response = await fetch("http://localhost:9999/cart", "GET", {
    _page: page,
    _limit: size,
  });
  return response.data;
};

// 加入购物车接口
export const fetchToCart = async ({ item }) => {
  const toCartRes = await fetch("http://localhost:9999/cart", "POST", item);
  console.log("ToCart", toCartRes);
  return toCartRes;
};

// 详情接口
export const fetchDetail = async ({ id }) => {
  const response = await fetch("http://localhost:9999/list", "GET", {
    id,
  });
  return response.data;
};

// 搜索接口
export const fetchSearch = async ({ keyword }) => {
  const response = await fetch("http://localhost:9999/list", "GET", {
    q: keyword,
  });
  return response.data;
};

// ++ / --
export const fetchCart = async ({ item }) => {
  console.log("api---->fetchCart:", item);
  const response = await fetch(
    `http://localhost:9999/cart/${item.id}`,
    "PATCH",
    item
  );
  return response.data;
};

// 服务器本地图片上传接口
const taroUploadFile = (msg = "native", paths) => {
  let url = "";
  if ((msg = "native")) {
    url = "http://localhost:3000/api/oss/server-upload";
  } else {
    url = "http://localhost:3000/api/oss/upload";
  }
  // console.log("url:", url, msg, paths);
  return new Promise((resolve, reject) => {
    // console.log("Taro:", Taro.uploadFile);
    Taro.uploadFile({
      url, //仅为示例，非真实的接口地址
      filePath: paths[0],
      name: "img", // name 需要与后端接收的地方对应上
      formData: {
        user: "test",
      },
      success: (res) => {
        console.log("res:success", res);
        const data = res.data;
        //do something
        resolve(data);
      },
      fail: (error) => {
        console.log("error;", error);
        reject(error);
      },
    });
  });
};

// taro封装的图片上传接口
export const uploadImage = async ({ msg = "native", paths }) => {
  const response = await taroUploadFile(msg, paths);
  return JSON.parse(response);
};

// 获取头像昵称
export const fetchUserInfo = async () => {
  try {
    const res = await wx.getUserProfile({ desc: "userInfo" });
    return res;
  } catch (error) {
    return error;
  }
};

// 获取用户手机号
